package com.example.seh.util;

import android.graphics.Bitmap;
import android.util.Log;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;

public class ChatClient {
    public Socket requestSocket(String host) throws UnknownHostException, IOException {
        Log.e("chat","开始连接");
        Socket socket = new Socket(host,5000);
        socket.setKeepAlive(true);
        //设置最大连接超时时间，超过此时间，无响应则断开连接
        socket.setSoTimeout(10);
        Log.e("chat","连接成功");

        //Socket client = new Socket(host, ip); //卡柱啦！不好啦怎办？

        //正确搞法
        //1. 直接new一个空的出来，这样不会卡柱。
//        Socket client = new Socket();
//        //2. 按照new Socket(host, port)的二次构造函数，调用
//        InetSocketAddress address = host != null ? new InetSocketAddress(host, 5000) :
//                new InetSocketAddress(InetAddress.getByName(null), 5000);
//        SocketAddress localAddr = null;
//        try {
//            if (localAddr != null) //可以移除
//                client.bind(localAddr);
//            //3. 关键的，我们可以这里设置timeout。
//            //即使不做timeout，我们可以在想关闭的时候，调用client.close也可以解决啦。
//            client.connect(address, 500);
//        } catch (IOException | IllegalArgumentException | SecurityException e) {
//            try {
//                client.close();
//            } catch (IOException ce) {
//                e.addSuppressed(ce);
//            }
//            throw e;
//        }

        return socket;
    }

    public void sendMsg(Socket socket,String msg)throws IOException{
        BufferedWriter writer=new BufferedWriter(
                new OutputStreamWriter(socket.getOutputStream())
        );
        Log.e("chat", "将要write的数据：" + msg);
        writer.write(msg.replace("\n","")+"\n");
//        writer.write("\n");
        writer.flush();
    }



    public String receiveMsg(Socket socket)throws  IOException{
        BufferedReader reader=new BufferedReader(
                new InputStreamReader(socket.getInputStream())
        );
        String txt=reader.readLine();
        return txt;
    }
}